package com.feishu.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.feishu.base.type.ClassificationTypeEnum;
import com.feishu.base.type.OutJsonTypeEnum;
import com.feishu.rpc.core.SendHttpServer;
import com.feishu.service.FeiShuCommonService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.session.TyAccountContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.impl.el.FixedValue;
import org.flowable.task.service.delegate.DelegateTask;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CustomListener(
        category = "飞书节点执行后接口监听",
        description = "飞书节点执行后接口监听"
)
public class FeishuNodeListener implements  TaskListener {

    @CustomListenerField(
            description = "飞书三方审批同步编码",
            defaultValue = "",
            required = true
    )
    private FixedValue synCode;

    @CustomListenerField(
            description = "飞书三方审批同步对象",
            defaultValue = "",
            required = true
    )
    private FixedValue synObject;

    @CustomListenerField(
            description = "审核对象（对象不同，页面不同）",
            defaultValue = "",
            required = true
    )
    private FixedValue audit;
    @CustomListenerField(
            description = "审核状态[APPROVED，REJECTED, TERMINATED]",
            defaultValue = "",
            required = true
    )
    private FixedValue auditStatus;

    @Override
    public void notify(DelegateTask delegateTask) {
        TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(TyplmWorkFlowContainerService.class);
        TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);
        TaskService taskService=SpringUtil.getBean(TaskService.class);
        BigInteger workFlowContainerId = new BigInteger(delegateTask.getVariable("workFlowContainerId").toString());
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(workFlowContainerId);

        if (workFlowContainerView instanceof WorkFlowObjectPackage) {
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            if (workFlowObjectPackage.getFlowObjectList() != null && workFlowObjectPackage.getFlowObjectList()
                    .size() != 0) {

                FlowObject flowObject = null;
                for(int i=0;i<workFlowObjectPackage.getFlowObjectList().size();i++){
                    flowObject=workFlowObjectPackage.getFlowObjectList().get(i);
                    String oType = flowObject.getRefObjectOtype();
                    if("ty.inteplm.part.CTyPart".equals(oType)){
                        break;
                    }
                    else if("ty.inteplm.form.CTyFormData".equals(oType)){
                        break;
                    }
                }
                String plmUserId= (String) taskService.getVariable(delegateTask.getId(),"plmUserId");
                UserDO plmUserDO =null;
                if(plmUserId!=null && "null".equals(plmUserId)==false){
                    plmUserDO = typlmUserService.queryUserByKey(new BigInteger(plmUserId));
                }
                else{
                    plmUserDO= TyAccountContext.getUser();
                }

                SendHttpServer sendHttpServer = SpringUtil.getBean(SendHttpServer.class);

                Map<String,Object> threadMap=new HashMap<>();
                threadMap.put("synCode",this.synCode.getExpressionText());
                threadMap.put("synObject",this.synObject.getExpressionText());
                threadMap.put("audit",this.audit.getExpressionText());
                threadMap.put("auditStatus",this.auditStatus.getExpressionText());

                threadMap.put("workFlowContainerId",workFlowContainerId.toString());
                threadMap.put("instance_id",delegateTask.getProcessInstanceId());
                threadMap.put("start_time",System.currentTimeMillis());
                threadMap.put("end_time",System.currentTimeMillis());
                threadMap.put("deploymentId",workFlowContainerView.getDeploymentId());
                String activityId=delegateTask.getTaskDefinitionKey();
                threadMap.put("activityId",activityId);
                threadMap.put("taskId",delegateTask.getId());
                threadMap.put("code",workFlowContainerView.getCode());
                threadMap.put("name",workFlowContainerView.getName());
                threadMap.put("creatorAccount",workFlowContainerView.getCreatorAccount());
                threadMap.put("workFlowName",workFlowContainerView.getWorkFlowName());
                threadMap.put("emergencyDegreeName",workFlowContainerView.getEmergencyDegreeName());
                threadMap.put("refObjectOid",flowObject.getRefObjectOid().toString());
                threadMap.put("plmUserId",plmUserDO.getOid().toString());
                threadMap.put("processInstanceId",delegateTask.getProcessInstanceId());

                for(int i=0;i<workFlowObjectPackage.getUserTaskList().size();i++){
                    if(activityId.equals(workFlowObjectPackage.getUserTaskList().get(i).getId())){
                        threadMap.put("UserTask",workFlowObjectPackage.getUserTaskList().get(i).getUserList());
                        break;
                    }
                }

                TaskService descTaskService= SpringUtil.getBean(TaskService.class);
                String executionsJson= (String) descTaskService.getVariable(delegateTask.getId(),"executionstrategy");

                JSONObject executionstrategy=null;
                JSONArray ExtensionElement=JSONArray.parseArray(executionsJson);
                if(ExtensionElement.size()>0){
                    String elementText=ExtensionElement.getJSONObject(0).getString("elementText");
                    executionstrategy=JSONObject.parseObject(elementText);
                }
                if(executionstrategy!=null){
                    threadMap.put("executionstrategy",executionstrategy);
                }


                FeiShuCommonService feiShuCommonService = SpringUtil.getBean(FeiShuCommonService.class);
                Map<String,Object> selectMap=new HashMap<>();
                selectMap.put("processInstanceId",delegateTask.getProcessInstanceId());
                List<Map<String,Object>> feishuCodeList=feiShuCommonService.getFeiShuApprovalCode(selectMap);
                threadMap.put("feishuCodeList",feishuCodeList);

                if(feishuCodeList.size()>0){
                    threadMap.put("submitId",feishuCodeList.get(0).get("submit_id"));
                    threadMap.put("approval_code",feishuCodeList.get(0).get("approval_code"));
                }

                JSONObject resultHttp=new JSONObject();
                resultHttp.put("code",0);

                if("一票决策".equals(executionstrategy.getString("name"))){
                    String router=executionstrategy.getString("router");
                    if(router!=null && "".equals(router)==false){
                        String routers[]=router.split(",");
                        boolean conform=false;
                        for(int i=0;i<routers.length;i++){
                            if(activityId.equals(routers[i])){
                                conform=true;
                                break;
                            }
                        }
                        if(conform==false){
                            //不符合一票通过，飞书修改当前用户数据状态
                            resultHttp=sendHttpServer.sendUserDataToNodeServer(this.synCode.getExpressionText(),
                                                                                 this.synObject.getExpressionText(),
                                                                                 OutJsonTypeEnum.OUT_JSON_TYPE_FEISHU,
                                                                                 ClassificationTypeEnum.DEFAULT.setValue("ordinaryMessage"),
                                                                                 flowObject,threadMap);
                        }
                    }
                }

                if(resultHttp.containsKey("code")==false){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp);
                }
                if(resultHttp.getLongValue("code")!=0){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(resultHttp.getString("msg"));
                }
            }
        }
    }

}
